import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///1.将两张本地图片使用canvas绘制到屏幕上
///2.给image2添加一个x轴的偏移动画，2秒内x轴偏移从0变化到100

Future<ui.Image> loadImage(String path) async {
  final data = await rootBundle.load(path);
  final bytes = data.buffer.asUint8List();
  final image = await decodeImageFromList(bytes);
  return image;
}

class MyCanvas extends CustomPainter {
  final ui.Image image2;
  final double animationScale;

  MyCanvas(this.image2, this.animationScale);

  @override
  void paint(Canvas canvas, Size size) {
    var offset = animationScale * 720 - 50;

    final paint = Paint();
    //开启canvas绘制的透明通道
    canvas.saveLayer(null, paint);
    //绘制一个宽高和按钮相同的圆角矩形rrect
    const rect = Rect.fromLTWH(50 + 8, 100 + 10, 642 - 16, 162 - 20);
    final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(162 / 2));
    paint.color = Colors.green;
    canvas.drawRRect(rrect, paint);

    //绘制覆盖光的图片，通过BlendMode.srcIn限制绘制光的图片时只显示出和rrect矩形相交的内容
    paint.blendMode = BlendMode.srcIn;
    canvas.drawImage(image2, Offset(offset, 50), paint);

    //通过BlendMode.clear抠掉左右多出来的rrect矩形
    paint.blendMode = BlendMode.clear;
    canvas.drawRect(
        Rect.fromLTWH(0, 0, offset, image2.height.toDouble()), paint);
    canvas.drawRect(
        Rect.fromLTWH(
            offset + image2.width, 0, 50 + 642, image2.height.toDouble()),
        paint);
    canvas.restore();
  }

  @override
  bool shouldRepaint(MyCanvas oldDelegate) {
    return oldDelegate.animationScale != animationScale;
  }
}

class LightButton extends StatefulWidget {
  const LightButton({super.key});

  @override
  LightButtonState createState() => LightButtonState();
}

class LightButtonState extends State<LightButton>
    with SingleTickerProviderStateMixin {
  AnimationController? _controller;
  Animation<double>? _animation;

  List<ui.Image>? images;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller!)
      ..addListener(() {
        setState(() {});
      });

    _initImage();

    super.initState();
  }

  void _initImage() async {
    debugPrint("开始loadImage");
    final images = [
      await loadImage("images/pic_button.png"),
      await loadImage("images/pic_button_light.png"),
    ];
    for (var image in images) {
      debugPrint("图片加载完毕:${image.width}x${image.height}");
    }
    setState(() {
      this.images = images;
    });
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (images == null) {
      return Container(
        color: Colors.blue,
      );
    } else {
      return Container(
        color: Colors.blue,
        child: GestureDetector(
          onTap: () {
            _controller?.forward(from: 0);
          },
          child: Stack(
            children: [
              const Positioned(
                  left: 50,
                  top: 100,
                  child: Image(image: AssetImage("images/pic_button.png"))),
              Opacity(
                opacity: 1 - _animation!.value,
                child: CustomPaint(
                  painter: MyCanvas(images![1], _animation!.value),
                ),
              )
            ],
          ),
        ),
      );
    }
  }
}
